package com.qiche.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.qiche.aspect.Result;
import com.qiche.config.YmlConfig;
import com.qiche.model.*;
import com.qiche.requestpram.CardSubsidyParam;
import com.qiche.service.CardSubsidyService;
import com.qiche.service.MerchantService;
import com.qiche.service2.Activity2Service;
import com.qiche.service2.Card2Service;
import com.qiche.service2.Store2Service;
import com.qiche.service2.Verification2Service;
import com.qiche.util.FastDFSUtils;
import com.qiche.util.LicensePateUtils;
import com.qiche.util.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * PiccVerificationController : 人保卡券系统核销控制类
 *
 * @author linzewen
 * @since 2017-04-19 15:10
 */
@RestController
@RequestMapping("/picc/verification")
public class PiccVerificationController {

    @Resource
    private Card2Service card2Service;

    @Resource
    private MerchantService merchantService;
    @Resource
    private LicensePateUtils licensePateUtils;
    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private CardSubsidyService cardSubsidyService;

    @Resource
    private Verification2Service verification2Service;

    @Resource
    private Activity2Service activity2Service;

    @Resource
    private Store2Service store2Service;


    @Resource
    private FastDFSUtils fastDFSUtils;


    /**
     * 小程序上传车牌图片
     *
     * @param file
     * @param type
     * @param request
     * @return
     */
    @PostMapping("/uploadImg")
    public Map<String, Object> uploadImg(@RequestParam("file") MultipartFile file, @RequestParam("type") String type, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        //type:是否需要车牌识别的标识
        try {
            String path = FastDFSUtils.uploadPic(file);
            map.put("path", path);
            map.put("fastdfsDomainUrl", ymlConfig.getFastdfsDomainUrl());
            //如如果照片类型为车牌则自动识别车牌号码
            if (StringUtils.isNotBlank(type) && type.equals("pln")) {
                //下载图片,车牌识别
                String[] paths = path.split("/", 2);
                byte[] data = fastDFSUtils.download_file(paths[0], paths[1]);
                if (data.length < 115) {
                    map.put("code", 0);
                    map.put("msg", "出现错误");
                }
                BASE64Encoder encoder = new BASE64Encoder();
                String pateBase64 = encoder.encode(data);
                JSONObject recognition = licensePateUtils.Recognition(pateBase64);
                System.out.println(recognition.getString("code"));
                System.out.println(recognition.getJSONObject("data").getString("number"));
                if (recognition.getString("code").equals("200")) {
                    map.put("data", recognition.getJSONObject("data").getString("number"));
                }
            }
            map.put("code", 1);
            map.put("msg", "上传完成");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "出现错误");
            map.put("error", e.getMessage());
            return map;
        }
        return map;
    }


    /**
     * 核销成功页面
     *
     * @param cardcode
     * @return
     */
    @GetMapping("/success/{cardcode}")
    public Result<Card2> verificationSuccess(@PathVariable("cardcode") String cardcode) {
        Card2 card = card2Service.selectCardAndMemberByCardCode(cardcode);
        return Result.createBySuccess(card);
    }


    /**
     * 核销卡券
     *
     * @param verification
     * @param cardCode
     * @return
     */
    @ResponseBody
    @PostMapping(value = "")
    public Map<String, Object> save(@ModelAttribute Verification2 verification, @RequestParam("card_code") String cardCode) {
        Map<String, Object> map = new HashMap<>();
        if (verification == null || cardCode == null) {
            map.put("code", 0);
            map.put("msg", "参数不正确");
            return map;
        }

        String licensePlateNumberPhoto = verification.getLicensePlateNumberPhoto();
        String carPhoto = verification.getCarPhoto();
        if (StringUtils.isEmpty(licensePlateNumberPhoto)) {
            //判断是否上传车牌照片
            map.put("code", 0);
            map.put("msg", "请上传车牌照片");
            return map;
        }
        if (StringUtils.isEmpty(carPhoto)) {
            //判断是否上传车牌照片
            map.put("code", 0);
            map.put("msg", "请上传车身照片");
            return map;
        }

        //判断优惠券是否已经被使用或者是否存在
        Card2Example cardExample = new Card2Example();
        Card2Example.Criteria cardExampleCriteria = cardExample.createCriteria();
        cardExampleCriteria.andStatusEqualTo("1");
        cardExampleCriteria.andCardCodeEqualTo(cardCode);
        List<Card2> cards = card2Service.selectCardAndMembersByExample(cardExample);
        if (cards == null || cards.size() == 0) {
            map.put("code", 0);
            map.put("msg", "优惠券不存在或者已经使用");
            return map;
        }

        Card2 card = cards.get(0);
        User user = UserUtils.getCurrentUser();
        Merchant merchant = merchantService.selectById(user.getMerchantId().longValue());
        card.setWriteoffShop(merchant.getPiccMid());
        card.setWriteoffDate(new Date());
        card.setStatus("2");
        card2Service.updateNotNull(card);//修改优惠券信息为已核销


        /*-------------------插入核销记录信息----------------------------   */
        verification.setCardId(card.getId());
        verification.setVerificationAmount(card.getGetAmount());
        verification.setCarPhoto(carPhoto);
        verification.setLicensePlateNumberPhoto(licensePlateNumberPhoto);
        verification.setVerificationDate(new Date());
        verification.setVerificationStoreid(merchant.getPiccMid());
        verification.setActivityId(card.getActivityId());

        verification.setMemberName(card.getMember().getNickname());
        verification.setMemberPhone(card.getMember().getPhone());
        verification.setMemberOpenid(card.getMember().getWxOpenid());



        verification.setVerificationUserid(merchant.getPiccMid());
        Store2 store2=store2Service.selectByKey(merchant.getPiccMid());
        if(store2!=null){
            verification.setVerificationUser(store2.getStoreName());
        }

        int saved = verification2Service.save(verification);    //记录优惠券核销信息

        /*---------------------------插入返点记录-----------------------------------*/
        Activity2 activity2=activity2Service.selectByKey(verification.getActivityId());
        CardSubsidyParam cardSubsidyParam=new CardSubsidyParam();
        cardSubsidyParam.setActivityId(verification.getActivityId().intValue());
        cardSubsidyParam.setCardAmount(new BigDecimal(card.getGetAmount()));
        cardSubsidyParam.setCardCode(card.getCardCode());
        cardSubsidyParam.setCarPhoto(verification.getCarPhoto());
        cardSubsidyParam.setLicensePlateNumber(verification.getLicensePlateNumber());
        cardSubsidyParam.setLicensePlateNumberPhoto(verification.getLicensePlateNumberPhoto());
        cardSubsidyParam.setVerifiAmount(new BigDecimal(activity2.getVerifiAmount()));
        cardSubsidyParam.setVerifiMultiple(activity2.getVerifiMultiple());
        cardSubsidyParam.setVerifiName(verification.getVerificationUser());
        cardSubsidyParam.setVerifiPhone("");
        cardSubsidyParam.setMerchantId(merchant.getPiccMid().intValue());
        try {
              cardSubsidyService.addCardSubsidy(cardSubsidyParam);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("-------人保卡券核销返点出错------------------");
        }
        if (saved != 0) {
            map.put("code", 1);
            map.put("msg", "保存成功");
        } else {
            map.put("code", 0);
            map.put("msg", "保存失败");
        }
        return map;
    }
}
